<template>
  <div class="article-manager-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-input-group">
        <el-input
            v-model="search1"
            placeholder="请输入标题查询"
            class="search-input"
            clearable
        >
          <template #prefix>
            <el-icon>
              <Search/>
            </el-icon>
          </template>
        </el-input>

        <el-input
            v-model="search2"
            placeholder="请输入类型查询"
            class="search-input"
            clearable
        >
          <template #prefix>
            <el-icon>
              <Folder/>
            </el-icon>
          </template>
        </el-input>

        <el-button
            class="search-btn"
            @click="getUserList()"
            type="primary"
            icon="Search"
        >搜索
        </el-button>

        <el-button
            class="reset-btn"
            @click="resetSearch()"
            icon="Refresh"
        >重置
        </el-button>
      </div>
    </div>

    <!-- 操作按钮区域 -->
<!--    <div class="action-buttons">
      <el-button
          @click="userAdd = true"
          type="success"
          icon="Plus"
          class="add-btn"
      >新增
      </el-button>

      <el-button
          @click="batchDelete"
          type="danger"
          icon="Delete"
          class="delete-btn"
      >批量删除
      </el-button>
    </div>-->

    <!-- 新增用户对话框 -->
    <el-dialog
        v-model="userAdd"
        title="新增用户"
        width="500px"
        class="custom-dialog"
        :close-on-click-modal="false"
    >
      <el-form :model="form" label-position="top">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              clearable
          />
        </el-form-item>
        <el-form-item label="用户头像" :label-width="formLabelWidth">
          <el-input
              v-model="form.userPic"
              placeholder="请输入头像URL"
              clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userAdd = false">取消</el-button>
          <el-button type="primary" @click="userAdd1" :loading="addLoading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
          :data="users"
          table-layout="fixed"
          style="width: 100%;height: calc(100vh - 300px);"
          stripe
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" align="center"/>
        <el-table-column prop="id" label="序号" width="80" align="center"/>
        <el-table-column label="封面" width="100" align="center">
          <template #default="scope">
            <el-image
                :src="scope.row.coverImg"
                alt="文章封面"
                class="cover-image"
                :preview-src-list="[scope.row.coverImg]"
                hide-on-click-modal
                fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="文章标题" min-width="150" show-overflow-tooltip/>
        <el-table-column label="文章内容" min-width="120" align="center">
          <template #default="scope">
            <el-button
                type="text"
                @click="content(scope.row)"
                class="content-btn"
            >点击查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="文章状态" min-width="100" align="center">
          <template #default="scope">
            <el-tag
                :type="scope.row.state === '公开' ? 'success' : 'danger'"
                effect="dark"
                round
            >
              {{ scope.row.state }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览量" min-width="80" align="center"/>
        <el-table-column prop="createTime" label="创建时间" min-width="160" align="center"/>
        <el-table-column prop="username" label="作者" min-width="120" align="center"/>
        <el-table-column prop="categoryName" label="所属类型" min-width="140" align="center">
          <template #default="scope">
    <span class="category-tag">
      {{ scope.row.categoryName }}
    </span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button
                @click="editUser(scope.row)"
                type="primary"
                size="small"
                icon="Edit"
                circle
            />
            <el-button
                @click="deleteArticle(scope.row.id)"
                type="danger"
                size="small"
                icon="Delete"
                circle
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[6, 9, 12, 15]"
          :total="totalUsers"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog
        v-model="editUser1"
        title="编辑用户信息"
        width="500px"
        class="custom-dialog"
        :close-on-click-modal="false"
    >
      <el-form :model="form1" label-position="top">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form1.username" placeholder="请输入用户名" clearable/>
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth">
          <el-input v-model="form1.nickname" placeholder="请输入昵称" clearable/>
        </el-form-item>
        <el-form-item label="用户头像" :label-width="formLabelWidth">
          <el-input v-model="form1.userPic" placeholder="请输入头像URL" clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editUser1 = false">取消</el-button>
          <el-button type="primary" @click="editUserConfirm" :loading="editLoading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 文章内容对话框 -->
  <el-dialog
      v-model="contentDialogVisible"
      title="文章内容"
      width="40%"
      align-center
      class="content-dialog"
      :close-on-click-modal="false"
  >
    <div v-html="contentHtml" class="markdown-content"></div>
    <template #footer>
      <el-button @click="contentDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, onMounted, reactive} from 'vue';
import {Search, Folder, Plus, Delete, Edit, Refresh} from '@element-plus/icons-vue';
import request from "@/api/request";
import {ElMessage, ElMessageBox, ElTable} from 'element-plus';
import VueMarkdownEditor, {xss} from "@kangc/v-md-editor";

interface User {
  id: number | null;
  userPic: string;
  username: string;
  nickname: string;
  phone: string;
  email: string;
  creatTime: any;
}

// 数据定义
const users = ref<User[]>([]);
const search1 = ref('');
const search2 = ref('');
const userAdd = ref(false);
const editUser1 = ref(false);
const formLabelWidth = '120px';
const addLoading = ref(false);
const editLoading = ref(false);
const selectedUsers = ref<User[]>([]);

const form = reactive({
  username: '',
  userPic: '',
});

const form1 = reactive<{
  id: number | null;
  username: string;
  userPic: string;
  nickname: string;
}>({
  id: null,
  username: '',
  userPic: '',
  nickname: '',
});

// 分页相关
const pageNum = ref(1);
const pageSize = ref(6);
const totalUsers = ref(0);

// 文章内容相关
const contentDialogVisible = ref(false);
const contentHtml = ref('');

const content = (row: any) => {
  const renderedHtml = VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(row.content);
  contentHtml.value = xss.process(renderedHtml);
  contentDialogVisible.value = true;
};


const getUserList = () => {
  request.get('/article/articleList', {
    params: {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      title: search1.value,
      categoryName: search2.value,
    },
  }).then((res: any) => {
    users.value = res.data.items;
    totalUsers.value = res.data.total;
    if (res.data.total.length === 0) {
      ElMessage.warning('不存在该文章');
    }
  }).catch((error: any) => {
    console.error('获取文章失败:', error);
    ElMessage.error('获取文章列表失败');
  });
};

const userAdd1 = () => {
  addLoading.value = true;
  request.post('/admin/addUser', {
    username: form.username,
    userPic: form.userPic,
  }).then((res: any) => {
    ElMessage.success('新增用户成功');
    userAdd.value = false;
    getUserList();
  }).catch((error: any) => {
    ElMessage.error(error.message || '新增用户失败');
  }).finally(() => {
    addLoading.value = false;
  });
};

const editUser = (user: User) => {
  form1.id = user.id;
  form1.username = user.username;
  form1.nickname = user.nickname;
  form1.userPic = user.userPic;
  editUser1.value = true;
};

const editUserConfirm = () => {
  editLoading.value = true;
  request.patch('/admin/updateUser', {
    id: form1.id,
    username: form1.username,
    userPic: form1.userPic,
    nickname: form1.nickname,
  }).then((res: any) => {
    ElMessage.success('编辑用户成功');
    editUser1.value = false;
    getUserList();
  }).catch((error: any) => {
    ElMessage.error('编辑用户失败');
  }).finally(() => {
    editLoading.value = false;
  });
};

// 删除文章
const deleteArticle = (articleId: number) => {
  ElMessageBox.confirm('确定要删除该文章吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    request.delete('/article/delArticle', {
      params: { articleId }
    }).then(() => {
      ElMessage.success('删除成功');
      getUserList();
    }).catch(error => {
      ElMessage.error('删除失败');
      console.error('删除文章失败:', error);
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const batchDelete = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请至少选择一项');
    return;
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 项吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ids = selectedUsers.value.map(user => user.id);
    request.post('/admin/batchDeleteUsers', {ids}).then(() => {
      ElMessage.success('批量删除成功');
      getUserList();
    }).catch(error => {
      ElMessage.error('批量删除失败');
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection;
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getUserList();
};

const handleCurrentChange = (val: number) => {
  pageNum.value = val;
  getUserList();
};

const resetSearch = () => {
  search1.value = '';
  search2.value = '';
  getUserList();
};

onMounted(() => {
  getUserList();
});
</script>

<style>
.article-manager-container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.search-input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  flex: 1;
  transition: all 0.3s;
}

.search-input:hover {
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.search-btn {
  background: linear-gradient(135deg, #409EFF, #337ecc);
  border: none;
  transition: all 0.3s;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.reset-btn {
  transition: all 0.3s;
}

.reset-btn:hover {
  transform: rotate(180deg);
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.add-btn {
  background: linear-gradient(135deg, #67C23A, #529b2e);
  border: none;
  color: white;
  transition: all 0.3s;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.delete-btn {
  background: linear-gradient(135deg, #F56C6C, #c45656);
  border: none;
  color: white;
  transition: all 0.3s;
}

.delete-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.table-container {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.cover-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  transition: all 0.3s;
}

.cover-image:hover {
  transform: scale(1.05);
}

.content-btn {
  color: #00b4f6;
  font-weight: bold;
  transition: all 0.2s;
}

.content-btn:hover {
  color: #529b2e;
  transform: translateX(2px);
}

.el-table__body tr:hover td {
  background-color: #f0f7ff !important;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.custom-dialog .el-dialog {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.custom-dialog .el-dialog__header {
  background: linear-gradient(135deg, #409EFF, #337ecc);
  margin: 0;
  padding: 15px 20px;
  color: white;
}

.custom-dialog .el-dialog__title {
  color: white;
  font-weight: bold;
}

.custom-dialog .el-dialog__body {
  padding: 20px;
}

.content-dialog .el-message-box {
  max-height: 80vh;
  overflow-y: auto;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.content-dialog .el-message-box__header {
  background: linear-gradient(135deg, #67C23A, #529b2e);
  padding: 15px 20px;
}

.content-dialog .el-message-box__title {
  color: white;
  font-weight: bold;
}

.content-dialog .el-message-box__content {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}
.category-tag {
  display: inline-block;
  padding: 4px 12px;
  background-color: #f0f9eb;
  color: #67c23a;
  border-radius: 4px;
  font-size: 14px;
  border: 1px solid #e1f3d8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.category-tag:hover {
  background-color: #e1f3d8;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.content-dialog .el-dialog {
  max-height: 80vh;
  overflow-y: auto;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.content-dialog .el-dialog__header {
  background: linear-gradient(135deg, #67C23A, #529b2e);
  padding: 15px 20px;
}

.content-dialog .el-dialog__title {
  color: white;
  font-weight: bold;
}

.content-dialog .el-dialog__body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.markdown-content {
  line-height: 1.6;
}

.markdown-content img {
  max-width: 100%;
}
</style>
